﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// Input manager for the game itself
/// </summary>
public class InputManager : MonoBehaviour 
{	
	public GridMaker gridMaker;
	public int gridWidth = 9;
	public int gridHeight = 9;
	public GameObject grid;
	public float distanceMin = 32;
	
	private Gem gem1 = null;
	private Gem gem2 = null;
	
	private void Start () 
	{
	}
	
	private void Update () 
	{
		OnMouseClick();
	}
	
	private void OnMouseClick()
	{
		if (Input.GetButtonDown("Fire1"))
		{		
			RaycastHit hit; 
			if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
			{
				if(gem1 != null)
				{
					// 2nd Gem selected
					gem2 = gridMaker.indexedGems[hit.collider.gameObject];
				
					// Swapt the gems
					Swap(gem1,gem2);
					
					// Check victory
					gridMaker.CheckMatchThree();
					
					gem1 = null;
					gem2 = null;
				}
				else
				{
					// First gem selected
					gem1 = gridMaker.indexedGems[hit.collider.gameObject];
				}
			}
		}
	}

	private void Swap(Gem gem1, Gem gem2)
	{
		//Debug.Log (Vector3.Distance (gem2.transform.position, gem1.transform.position));
		if(Vector3.Distance (gem2.go.transform.position, gem1.go.transform.position) <= distanceMin)
		{
			Vector3 temp = gem1.go.transform.position;
			gem1.go.transform.position = gem2.go.transform.position;
			gem2.go.transform.position = temp;
			
			gridMaker.gems[gem1.i, gem1.j] = gem2;
			gridMaker.gems[gem2.i, gem2.j] = gem1;
		}	
	}
}
